<template>
  <div>
    <Header :title="'返回'" :subTitle="'售后单列表'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card :bordered="false">
      <div class="font_title">{{ statusType[orderDetail.status] }}</div>
      <a-descriptions :column="3" title=" 售后单信息">
        <a-descriptions-item label="售后单号"> {{ orderDetail.refundSn }}</a-descriptions-item>
        <a-descriptions-item label="订单编号">
          <router-link :to="`/box/salesOrder/detail/${orderDetail.orderId}`">{{ orderDetail.orderSn }}</router-link>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间"> {{ orderDetail.createTime }}</a-descriptions-item>
        <a-descriptions-item label="支付流水号"> {{ orderDetail.tradeNo ? orderDetail.tradeNo : '-' }}</a-descriptions-item>
        <a-descriptions-item label="支付方式"> {{ orderDetail.paymentType }}</a-descriptions-item>
        <a-descriptions-item label="支付时间"> {{ orderDetail.createDate }}</a-descriptions-item>
        <a-descriptions-item label="订单类型">{{ typeType[orderDetail.type] }}</a-descriptions-item>
      </a-descriptions>
      <a-divider style="margin-bottom: 16px" dashed />
      <detail-list title=" 会员信息">
        <detail-list-item term="昵称">{{ orderDetail.nickName }}</detail-list-item>
        <detail-list-item term="手机号">{{ orderDetail.phone }}</detail-list-item>
        <detail-list-item term="归属搭配师">{{ orderDetail.name }}</detail-list-item>
      </detail-list>
      <a-divider style="margin-bottom: 32px" />
      <div class="title">售后原因</div>
      <a-form-model ref="rulesForm" :label-col="{ span: 2 }" :wrapper-col="{ span: 18 }" :model="form">
        <a-form-model-item label="售后原因" required>
          {{ orderDetail.refundRemark }}
        </a-form-model-item>
        <a-form-model-item label="退款说明">
          <a-input v-model="form.desc" type="textarea" />
        </a-form-model-item>
        <a-form-model-item label="凭证图片">
          <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :number="5" @fileChange="fileChange" v-model="fileList"></JImageUpload>
          <div>注：不超过5张</div>
        </a-form-model-item>
        <div>
          <a-divider style="margin-bottom: 32px" />
          <div class="title">售后商品</div>
          <a-table ref="table" size="default" style="margin-bottom: 24px" :rowKey="record => record.id" :columns="goodsColumns" :dataSource="dataSourceList">
            <span slot="serial" slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <span slot="goods" slot-scope="text, record">
              <ListInfo :record="record"></ListInfo>
            </span>
            <span slot="orderDetailRefundAmount" slot-scope="text, record, index">
              <div v-if="orderDetail.status == 0 || orderDetail.status == 1 || orderDetail.status == 2">
                <a-input-number v-model="record.orderDetailRefundAmount" :max="record.refundNumber" />
                <a v-if="orderDetail.refundRemark != '买贵退差价'" style="margin-left: 10px" @click="calculation(record, index)">自动计算</a>
              </div>
              <div v-else>
                {{ record.orderDetailRefundAmount }}
              </div>
            </span>
          </a-table>
          <div class="price">
            <div></div>
            <div>
              <p>售后商品：{{ commodity }}件</p>
              <p>实付金额：{{ payNumber }}元</p>
              <p>退款金额：{{ retreatNumber }}元</p>
            </div>
          </div>
          <div v-if="orderDetail.refundRemark != '买贵退差价'">
            <div>
              <a-divider style="margin-bottom: 32px" />
              <div>
                <span class="title">取件地址</span>
              </div>
              <a-form-model-item label="收货人" style="margin-top: 24px; margin-bottom: 12px"> {{ logistics.name }} </a-form-model-item>
              <a-form-model-item label="手机号" style="margin-bottom: 12px"> {{ logistics.phone }} </a-form-model-item>
              <a-form-model-item label="详细地址">{{ logistics.province }} {{ logistics.city }} {{ logistics.district }} {{ logistics.address }}</a-form-model-item>
            </div>
            <a-divider style="margin-bottom: 32px" />
            <div class="title">物流信息</div>
            <a-form-model-item label="物流单号" style="margin-top: 24px; margin-bottom: 12px">
              <span>{{ orderDetail.trackingNumber }}</span>
              <a class="single" @click="showModal('oddNumber')">修改单号</a>
              <a @click="logisticClick">查看物流</a>
            </a-form-model-item>
            <a-form-model-item label="预约取件时间"> {{ orderDetail.getDate }} </a-form-model-item>
            <a style="margin-left: 60px" @click="showModal('express')">重约快递</a>
          </div>
        </div>
      </a-form-model>
      <a-divider style="margin-bottom: 32px" />
      <div style="margin-bottom: 24px">
        <span class="title_size">操作日志</span>
        <a @click="showModal('remark')">添加备注</a>
      </div>
      <JournalTable :tableData="tableData"></JournalTable>

      <div v-if="orderDetail.status == 1 || orderDetail.status == 2">
        <a-button @click="showModal('refund')" type="primary" style="margin-right: 10px" :loading="loadingRefund">确认并退款</a-button>
        <a-button @click="showModal('reject')" style="margin-right: 10px" :loading="loading">驳回申请</a-button>
        <a-button @click="cancelClick">返 回</a-button>
      </div>
      <div v-else-if="orderDetail.status == 0">
        <a-button @click="showModal('reject')" style="margin-right: 10px" :loading="loading">驳回申请</a-button>
        <a-button @click="cancelClick">返 回</a-button>
      </div>
      <div v-else>
        <a-button @click="cancelClick">返 回</a-button>
      </div>
    </a-card>
    <Address ref="address" :unionId="orderDetail.unionid" :defLogistic="logistics" @newAddress="newAddress" :title="'选择地址'"></Address>
    <LogisticsDetail ref="logisticRef" :dataSourceData="dataSourceData"></LogisticsDetail>
    <a-modal v-model="visible" centered :title="modalText" @ok="handleOk">
      <div v-if="modalType === 'remark'">
        <a-textarea v-model="remarkValue" :auto-size="{ minRows: 3, maxRows: 5 }" :maxLength="50" />
      </div>
      <div v-if="modalType === 'oddNumber'">
        <a-input placeholder="请修改物流单号" v-model="oddNumbers" />
      </div>
      <div v-if="modalType === 'express'">
        <a-form layout="vertical" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-form-item label="取件地址" required>
            <a style="margin-left: 50px" @click="changeAdds">修改</a>
          </a-form-item>
          <div>{{ logistics.name }} {{ logistics.phone }}</div>
          <div class="address">{{ logistics.province }} {{ logistics.city }} {{ logistics.district }} {{ logistics.address }}</div>
          <a-form-item label="取件时间" required>
            <a-date-picker format="YYYY-MM-DD HH:mm:ss" v-model="pieceTime" @change="onChangeEntryTime" style="width: 200px" />
          </a-form-item>
        </a-form>
      </div>
      <div v-if="modalType === 'reject'">
        <a-textarea v-model="rejectValue" :auto-size="{ minRows: 3, maxRows: 5 }" placeholder="请输入驳回理由,最多20字" :maxLength="20" />
      </div>
      <div v-if="modalType === 'refund'">
        <div>继续操作退款将原路退还给用户</div>
        <div>请确认仓库已收到退货</div>
      </div>
    </a-modal>
  </div>
</template>
<script>
import Header from '@/views/box/components/layouts/Header'
import DetailList from '@/components/tools/DetailList'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import globalData from '@/assets/js/common'
import ListInfo from '@views/box/components/goodsInfo/listInfo'
import { STable, Ellipsis } from '../components'
import Address from '@/views/box/components/Address/AddressList'
import JournalTable from './components/journalTable.vue'
import LogisticsDetail from './components/logisticsDetail.vue'
import { orderDetail, logList, setTrackingNumber, overRefund, auditAndCheckOrderInfo, resetTrack, addRemark, logisticsDetails } from '@/api/box/sales'
const DetailListItem = DetailList.Item
const goodsColumns = [
  {
    title: '序号',
    dataIndex: 'serial',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '商品',
    dataIndex: 'barcode',
    scopedSlots: { customRender: 'goods' },
    width: '400px'
  },
  {
    title: '款号',
    dataIndex: 'productCode'
  },
  {
    title: '原价',
    dataIndex: 'productPrice',
    align: 'center'
  },
  {
    title: '活动减免',
    dataIndex: 'productFavorablePrice',
    align: 'center'
  },
  {
    title: '会员折扣',
    dataIndex: 'vipPrice',
    align: 'center'
  },
  {
    title: '实付金额',
    dataIndex: 'priceactual',
    align: 'center'
  },
  {
    title: '退款金额',
    dataIndex: 'orderDetailRefundAmount',
    scopedSlots: { customRender: 'orderDetailRefundAmount' },
    align: 'center'
  },
  {
    title: '售后数量',
    dataIndex: 'refundQty',
    align: 'center'
  },
  {
    title: '订单数量',
    dataIndex: 'productQuantity',
    align: 'center'
  }
]
export default {
  components: {
    Header,
    DetailList,
    DetailListItem,
    JImageUpload,
    ListInfo,
    STable,
    Ellipsis,
    Address,
    JournalTable,
    LogisticsDetail
  },
  data() {
    this.goodsColumns = goodsColumns
    return {
      statusType: {
        0: '待寄回',
        1: '待仓库收货',
        2: '待退款',
        3: '已成功退款',
        4: '申请驳回',
        5: '取消退款'
      },
      typeType: {
        10: 'BOX',
        20: '导购',
        30: '有搭',
        40: '主题盒子'
      },
      refundSn: '',
      visible: false,
      loading: false,
      loadingRefund: false,
      tableData: [], // 操作日志
      dataSourceData: [], // 物流信息
      logistics: {
        phone: '',
        name: '',
        province: '',
        city: '',
        district: '',
        address: ''
      }, // 取件地址
      dataSourceList: [],
      orderDetail: {},
      type: 1,
      form: {
        region: '', // 售后原因
        desc: '', // 退款说明
        time: '' // 取件时间
      },
      fileList: [],
      newLifePhotos: [], // 凭证图片
      address: {},
      oddNumbers: '', // 物流单号
      remarkValue: '', // 添加备注
      pieceTime: '', // 取件时间
      modalType: '', // 弹框类型
      modalText: '', // 弹框title
      rejectValue: '', // 驳回理由
      rules: {
        express: [{ required: true, message: '请预约快递', trigger: 'change' }],
        time: [{ required: true, message: '请选择取件时间', trigger: 'change' }]
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  computed: {
    // 实付金额
    payNumber() {
      let total = this.dataSourceList.reduce((total, obj) => {
        return (total += Math.round(Number(obj.productQuantity) * Number(obj.priceactual) * 100) / 100)
      }, 0)
      return Math.round(total * 100) / 100
    },
    // 退款金额
    retreatNumber() {
      let total = 0
      this.dataSourceList.forEach(item => {
        total = Math.round(total * 100) / 100 + Math.round(Number(item.orderDetailRefundAmount) * 100) / 100
      })
      return Math.round(total * 100) / 100
    },
    // 售后商品数量
    commodity() {
      let total = this.dataSourceList.reduce((total, obj) => {
        return (total += Number(obj.refundQty))
      }, 0)
      return total
    }
  },
  created() {
    this.refundSn = this.$route.params.id
    this.auditAndCheckOrderInfo() // 审核信息
    this.postlogList() //操作日志
    this.logisticsDetails() // 查看物流
  },
  methods: {
    // 自动计算
    calculation(record, index) {
      this.dataSourceList[index].orderDetailRefundAmount = Math.round(record.priceactual * record.productQuantity * 100) / 100
    },
    logisticsDetails() {
      let requestData = {
        refundSn: this.refundSn
      }
      let params = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: requestData
      }
      logisticsDetails(params).then(res => {
        if (res.code == 0) {
          this.dataSourceData = res.data && res.data.length > 0 ? res.data[0].routes : []
        }
      })
    },
    onChangeEntryTime(date, dateString) {
      this.pieceTime = dateString
    },
    // 售后详情
    auditAndCheckOrderInfo() {
      let requestData = {
        refundSn: this.refundSn
      }
      let params = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: requestData
      }
      auditAndCheckOrderInfo(params).then(res => {
        if (res.code === 0) {
          this.orderDetail = res.data.order
          this.form.desc = this.orderDetail.memo
          this.logistics = res.data.logistics ? res.data.logistics : this.logistics
          this.orderDetail.refundPhotos = JSON.parse(this.orderDetail.refundPhotos)
          if (this.orderDetail.refundPhotos) {
            this.fileList = this.orderDetail.refundPhotos.map(item => {
              return item.sourceProductImagePath
            })
          }
          this.dataSourceList = res.data.orderDetail
          this.dataSourceList.forEach(item => {
            item.priceactual = Number(item.priceactual)
            item.refundNumber = JSON.parse(JSON.stringify(Number(item.priceactual) * Number(item.productQuantity)))
            item.orderDetailRefundAmount = Number(item.orderDetailRefundAmount)
          })
        }
      })
    },
    postlogList() {
      let requestData = {
        refundSn: this.refundSn
      }
      let params = {
        page: {
          pageNo: 1,
          count: 0,
          pageSize: 10,
          pages: 0
        },
        requestData: requestData
      }
      logList(params).then(res => {
        this.tableData = res.data
      })
    },
    // 修改取件地址
    changeAdds() {
      this.$refs.address.show()
    },
    // 更新地址
    newAddress(record) {
      this.logistics = record
      this.logistics.name = record.contactName
      this.logistics.phone = record.contactPhone
      this.$emit('changeAddress', record)
    },
    // 售后商品多选框
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    headerBack() {
      this.$router.back()
    },
    // 上传图片
    fileChange(list) {
      this.newLifePhotos = list
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    showModal(type) {
      switch (type) {
        case 'remark':
          this.modalText = '请输入备注(最多50字)'
          this.modalType = 'remark'
          break
        case 'oddNumber':
          this.modalText = '修改快递单号'
          this.modalType = 'oddNumber'
          break
        case 'express':
          this.modalText = '选择题'
          this.modalType = 'express'
          break
        case 'reject':
          this.modalText = '请输入驳回理由:'
          this.modalType = 'reject'
          break
        case 'refund':
          this.modalText = '确认退款:'
          this.modalType = 'refund'
          break
      }
      setTimeout(() => {
        this.visible = true
      }, 200)
    },
    handleOk() {
      switch (this.modalType) {
        case 'remark':
          this.insertRemark()
          break
        case 'oddNumber':
          this.oddNumber()
          break
        case 'express':
          this.expressTime()
          break
        case 'reject':
          this.overClick()
          break
        case 'refund':
          this.submitForm()
          break
      }
    },
    // 填写备注
    insertRemark() {
      if (!this.remarkValue) {
        this.$message.warning('请填写备注')
        return
      } else {
        let requestData = {
          remark: this.remarkValue,
          refundSn: this.refundSn
        }
        let params = {
          page: {
            pageNo: 1,
            pageSize: 10
          },
          requestData: requestData
        }
        addRemark(params).then(res => {
          if (res.code == 0) {
            this.$message.success('填写备注成功')
            this.postlogList()
          }
          this.remarkValue = null
          this.visible = false
        })
      }
    },
    // 修改物流单号
    oddNumber() {
      if (!this.oddNumbers) {
        this.$message.warning('请输入物流单号')
        return
      }
      let requestData = {
        refundSn: this.refundSn,
        trackingNumber: this.oddNumbers
      }
      let params = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: requestData
      }
      setTrackingNumber(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功')
          this.auditAndCheckOrderInfo()
          this.postlogList()
        } else {
          this.$message.warning(res.msg)
        }
        this.oddNumbers = ''
        this.visible = false
      })
    },
    // 修改时间
    expressTime() {
      if (!this.pieceTime) {
        this.$message.warning('请选择取件时间')
        return
      } else {
        let requestData = {
          getDate: this.pieceTime,
          refundSn: this.refundSn
        }
        let params = {
          page: {
            pageNo: 1,
            pageSize: 10
          },
          requestData: requestData
        }
        resetTrack(params).then(res => {
          if (res.code == 0) {
            this.$message.success('重叫成功')
          } else {
            this.$message.warning(res.msg)
          }
          this.pieceTime = null
          this.visible = false
        })
      }
    },
    // 确定退款
    submitForm() {
      this.loadingRefund = true
      let boxRefundDetails = this.dataSourceList.map(item => {
        const newItem = {
          id: item.boxRefundDetailId,
          refundAmount: item.orderDetailRefundAmount
        }
        return newItem
      })
      let requestData = {
        refundSn: this.refundSn,
        amount: this.retreatNumber.toString(),
        autoAmount: 0,
        status: 3,
        boxRefundDetails: boxRefundDetails
      }
      let params = {
        page: {
          pageNo: 1,
          pageSize: 10
        },
        requestData: requestData
      }
      overRefund(params).then(res => {
        if (res.code == 0) {
          this.$message.success('退款成功')
          this.$router.push(`/box/afterSalesOrder/list`)
        } else {
          this.$message.warning(res.msg)
        }
        this.loadingRefund = false
        this.oddNumbers = ''
        this.visible = false
      })
    },
    // 驳回申请
    overClick() {
      if (!this.rejectValue) {
        this.$message.warning('请输入驳回理由')
        return
      } else {
        this.loading = true
        let boxRefundDetails = this.dataSourceList.map(item => {
          const newItem = {
            id: item.boxRefundDetailId,
            refundAmount: item.orderDetailRefundAmount
          }
          return newItem
        })
        let requestData = {
          refundSn: this.refundSn,
          remark: this.rejectValue,
          boxRefundDetails: boxRefundDetails,
          status: 4
        }
        let params = {
          page: {
            pageNo: 1,
            pageSize: 10
          },
          requestData: requestData
        }
        overRefund(params).then(res => {
          if (res.code == 0) {
            this.$message.success('驳回成功')
            this.$router.push(`/box/afterSalesOrder/list`)
          }
          this.loading = false
          this.rejectValue = ''
          this.visible = false
        })
      }
    },
    // 取消
    cancelClick() {
      this.$router.push(`/box/afterSalesOrder/list`)
    },
    // 查看物流
    logisticClick() {
      let data = {
        refundSn: this.orderDetail.refundSn, // 售后单号
        createDate: this.orderDetail.createDate, // 创建时间
        trackingNumber: this.orderDetail.trackingNumber, // 运单号
        phone: this.logistics.phone,
        name: this.logistics.name,
        province: this.logistics.province,
        city: this.logistics.city,
        district: this.logistics.district,
        address: this.logistics.address
      }
      this.$refs.logisticRef.save(data)
      this.$refs.logisticRef.show()
    }
  }
}
</script>
<style lang="less" scoped>
.title {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}
.title_size {
  color: rgba(0, 0, 0, 0.85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  margin-right: 50px;
}
.price {
  display: flex;
  justify-content: space-between;
}
.size_color {
  color: #40a9ff;
}
.single {
  margin-left: 100px;
  margin-right: 50px;
}
.address {
  margin-top: 20px;
  margin-bottom: 30px;
}
.font_title {
  color: rgba(0, 0, 0, 0.85);
  font-weight: 600;
  font-size: 24px;
  margin-bottom: 24px;
}
</style>

